package cn.zf233.jwtshiro.service.impl;

import cn.zf233.jwtshiro.entity.User;
import cn.zf233.jwtshiro.mapper.UserMapper;
import cn.zf233.jwtshiro.service.UserService;
import cn.zf233.jwtshiro.util.TestVCodePool;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by zf233 on 2021/7/12
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User getUserById(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public User getUserByUsername(String username) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        return userMapper.selectOne(wrapper);
    }

    @Override
    public User getUserByPhone(String phone) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", phone);
        return userMapper.selectOne(wrapper);
    }

    @Override
    public User getUserByOpenId(String openId) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("open_id", openId);
        return userMapper.selectOne(wrapper);
    }

    @Override
    public String getVCodeByPhone(String phone) {
        return TestVCodePool.get(phone);
    }

    @Override
    public Set<String> getRoleByUserId(Long userId) {
        User user = userMapper.selectById(userId);
        String role = user.getRole();
        Set<String> roleSet = new HashSet<>(3);
        if (StringUtils.isNotBlank(role)) {
            String[] roles = role.split("\\|");
            roleSet.addAll(Arrays.asList(roles));
        }
        return roleSet;
    }

    @Override
    public Set<String> getPermissionByUserId(Long userId) {
        User user = userMapper.selectById(userId);
        String role = user.getPermission();
        Set<String> permissionSet = new HashSet<>(3);
        if (StringUtils.isNotBlank(role)) {
            String[] permissions = role.split("\\|");
            permissionSet.addAll(Arrays.asList(permissions));
        }
        return permissionSet;
    }

    @Override
    public List<User> list() {
        return userMapper.selectList(new QueryWrapper<>());
    }
}
